package com.atguigu.gmall.order.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 订单管理
 */
@RestController
@RequestMapping("/api/order")
public class OrderApiController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;
    //生成交易号
    @GetMapping("/auth/tradeNo")
    public String tradeNo(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //交易号在缓存中的Key值
        String tradeNoKey = "user:" + userId + ":tradeCode";
        //UUID
        String tradeNo = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(tradeNoKey,tradeNo);//用户100万
        // 对（用户ID + 商品ID）组合进行MD5进行加密
        return tradeNo;
    }

    //订单提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestBody OrderInfo orderInfo, String tradeNo,HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //交易号在缓存中的Key值
        String tradeNoKey = "user:" + userId + ":tradeCode";
//        1、先判断交易号的正确性 （交易号不存在、交易号不正确） 返回
        if(StringUtils.isEmpty(tradeNo)){
            return Result.fail().message("非法操作");
        }else{

            String no = (String) redisTemplate.opsForValue().get(tradeNoKey);
            if(StringUtils.isEmpty(no)){
                return Result.fail().message("请不要重复提交订单");
            }else{
                if(!no.equals(tradeNo)){
                    return Result.fail().message("非法操作");
                }
            }
        }
//        正确：删除交易号   第二次以后提交的订单就没有交易号
        redisTemplate.delete(tradeNoKey);
//        2、校验库存 （已经没有库存）
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            boolean hasStock = orderInfoService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if(!hasStock){
                return Result.fail().message(orderDetail.getSkuName() + ":库存不足");
            }
        }
//        3、保存订单   订单表、订单详情表
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.submitOrder(orderInfo);
//        4、购买了商品从购物车中删除出去
        return Result.ok(orderId);
    }
    //对外暴露订单对象
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable(name = "orderId") Long orderId){

        return orderInfoService.getOrderInfo(orderId);
    }

    //由库存微服务发出来的请求 要求折单
    @PostMapping("/orderSplit")
    public List<Map<String,Object>> orderSplit(String orderId, String wareSkuMap){
        //1:订单折分  入参：
        List<OrderInfo> orderInfoList = orderInfoService.orderSplit(orderId,wareSkuMap);//1个原始订单 至少折单 2个
        //2:返回值
        List<Map<String, Object>> mapList = orderInfoList.stream().map(orderInfo -> {
            return orderInfoService.initWareOrder(orderInfo);
        }).collect(Collectors.toList());
        return mapList;

    }
}
